package com.aurora.source.util.netutil;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.aurora.source.authority.bean.CommodityManagementBean;
import com.aurora.source.authority.bean.PersonAuthAddBean;
import com.aurora.source.authority.bean.PersonAuthBean;
import com.aurora.source.authority.bean.ProcessDataBean;
import com.aurora.source.authority.bean.SysAuthDataBean;
import com.aurora.source.base.BaseBean;
import com.aurora.source.base.UpdateBean;
import com.aurora.source.center.bean.AddBatchBean;
import com.aurora.source.center.bean.FlowDataBean;
import com.aurora.source.center.bean.OprationRecoredListBean;
import com.aurora.source.constant.AuroraConstants;
import com.aurora.source.di.dicomponent.DaggerDiComponent;
import com.aurora.source.di.dimodule.DiModule;
import com.aurora.source.home.bean.BatchManagementBean;
import com.aurora.source.home.bean.ContactUsDataBean;
import com.aurora.source.home.bean.NewAreaBean;
import com.aurora.source.home.bean.NewCityBean;
import com.aurora.source.home.bean.NewProvinceBean;
import com.aurora.source.source.SourceApplication;
import com.aurora.source.source.bean.UserInfoBean;
import com.aurora.source.util.BitmapUtil;
import com.aurora.source.util.StringUtils;
import com.aurora.source.util.encryption.MD5Utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author: Lance
 * @description: 封装请求方法
 * @date: 2018/7/6 14:15
 */
public class RequestMethod {

    private RetrofitService mRetrofitService;

    private Map<String, String> mRequestMap;// 请求map

    // 公共参数
    private void getRequestMap() {
        mRequestMap = new HashMap<>();
        mRequestMap.put(AuroraConstants.REQUEST_SOURCE_KEY, AuroraConstants.REQUEST_SOURCE_VALUE);
        mRequestMap.put("clientType", "ANDROID");
        mRequestMap.put("clientVS", SourceApplication.versonCode);
    }

    @Inject
    RequestEngine requestEngine;

    public RequestMethod() {
        // 此处也可以用注解来做，
        // this.RetrofitService = RequestEngine.getInstance().getServer(RetrofitService.class);
        // 用注解的方式
        DaggerDiComponent.builder().diModule(new DiModule()).build().inject(this);
        mRetrofitService = requestEngine.getServer(RetrofitService.class);
    }

    // 获取 Apk
    public void automaticUpdate(SubscriberObserver<BaseBean<UpdateBean>> subscriber) {
        getRequestMap();

        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));

        mRetrofitService.automaticUpdate(mRequestMap)
                .compose(RxHelper.<BaseBean<UpdateBean>>schedulersThread())
                .subscribe(subscriber);
    }

    // 登录钱包
    public void loginSource(Map<String, String> loginMap, SubscriberObserver<BaseBean<UserInfoBean>> subscriber) {
        getRequestMap();
        mRequestMap.putAll(loginMap);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.loginSource(mRequestMap)
                .compose(RxHelper.<BaseBean<UserInfoBean>>schedulersThread())
                .subscribe(subscriber);

    }

    //企业信息
    public void contactUs(Map<String, String> loginMap, SubscriberObserver<BaseBean<ContactUsDataBean>> subscriber) {
        getRequestMap();
        mRequestMap.putAll(loginMap);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.contactUsSource(mRequestMap)
                .compose(RxHelper.<BaseBean<ContactUsDataBean>>schedulersThread())
                .subscribe(subscriber);

    }

    //权限管理
    public void authManage(Map<String, String> loginMap, SubscriberObserver<BaseBean<PersonAuthBean>> subscriber) {
        getRequestMap();
        mRequestMap.putAll(loginMap);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.authManage(mRequestMap)
                .compose(RxHelper.<BaseBean<PersonAuthBean>>schedulersThread())
                .subscribe(subscriber);

    }

    //权限管理-查看
    public void examine(Map<String, String> loginMap, SubscriberObserver<BaseBean<UserInfoBean>> subscriber) {
        getRequestMap();
        mRequestMap.putAll(loginMap);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.examine(mRequestMap)
                .compose(RxHelper.<BaseBean<UserInfoBean>>schedulersThread())
                .subscribe(subscriber);

    }

    //注销
    public void regist(Map<String, String> loginMap, SubscriberObserver<BaseBean> subscriber) {
        getRequestMap();
        mRequestMap.putAll(loginMap);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.regist(mRequestMap)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriber);

    }

    //添加权限
    public void addJurisdiction(Map<String, String> loginMap, SubscriberObserver<BaseBean<ProcessDataBean>> subscriber) {
        getRequestMap();
        mRequestMap.putAll(loginMap);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.addJurisdiction(mRequestMap)
                .compose(RxHelper.<BaseBean<ProcessDataBean>>schedulersThread())
                .subscribe(subscriber);

    }

    //添加批次
    public void addBatch(Map<String, String> loginMap, SubscriberObserver<BaseBean<AddBatchBean>> subscriber) {
        getRequestMap();
        mRequestMap.putAll(loginMap);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.addBatch(mRequestMap)
                .compose(RxHelper.<BaseBean<AddBatchBean>>schedulersThread())
                .subscribe(subscriber);

    }

    //批次管理
    public void batchManagement(Map<String, String> loginMap, SubscriberObserver<BaseBean<BatchManagementBean>> subscriber) {
        getRequestMap();
        mRequestMap.putAll(loginMap);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.batchManagement(mRequestMap)
                .compose(RxHelper.<BaseBean<BatchManagementBean>>schedulersThread())
                .subscribe(subscriber);

    }

    //商品管理
    public void commodityManagement(Map<String, String> loginMap, SubscriberObserver<BaseBean<CommodityManagementBean>> subscriber) {
        getRequestMap();
        mRequestMap.putAll(loginMap);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.commodityManagement(mRequestMap)
                .compose(RxHelper.<BaseBean<CommodityManagementBean>>schedulersThread())
                .subscribe(subscriber);

    }

    //权限管理-添加
    public void affirmAdd(Map<String, String> loginMap,File cardJust, File cardAgainst, SubscriberObserver<BaseBean<PersonAuthAddBean>> subscriber) {
        getRequestMap();
        mRequestMap.putAll(loginMap);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);//表单类型
        for (Map.Entry<String, String> entry : mRequestMap.entrySet()) {
            builder.addFormDataPart(entry.getKey(),entry.getValue());
        }
        if(cardJust!=null){
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), cardJust);
            builder.addFormDataPart("idCardImg1", cardJust.getName(), imageBody);//memberImgFile 后台接收图片流的参数名
        }
        if(cardAgainst!=null){
            RequestBody imageBody2 = RequestBody.create(MediaType.parse("multipart/form-data"), cardAgainst);
            builder.addFormDataPart("idCardImg2", cardAgainst.getName(), imageBody2);//memberImgFile 后台接收图片流的参数名
        }
        List<MultipartBody.Part> parts = builder.build().parts();
        mRetrofitService.affirmAdd(parts)
                .compose(RxHelper.<BaseBean<PersonAuthAddBean>>schedulersThread())
                .subscribe(subscriber);

    }

    //头像
    public void protrait(Map<String, String> loginMap,File file, SubscriberObserver<BaseBean> subscriber) {
        getRequestMap();
        mRequestMap.putAll(loginMap);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);//表单类型
        for (Map.Entry<String, String> entry : mRequestMap.entrySet()) {
            builder.addFormDataPart(entry.getKey(),entry.getValue());
        }
        if(file!=null){
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("resourceFile", file.getName(), imageBody);//memberImgFile 后台接收图片流的参数名
        }

        List<MultipartBody.Part> parts = builder.build().parts();
        mRetrofitService.portrait(parts)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriber);

    }


    //录入流程信息
    public void getFlowInfo(String userId, SubscriberObserver<BaseBean<FlowDataBean>> subscriber) {
        getRequestMap();
        mRequestMap.put("userId",userId);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.getFlowInfo(mRequestMap)
                .compose(RxHelper.<BaseBean<FlowDataBean>>schedulersThread())
                .subscribe(subscriber);
    }

    public void updateCompanyHonorOrQuarantine(Map<String, String> editParams, File file, SubscriberObserver<BaseBean> subscriber) {
        getRequestMap();
        mRequestMap.putAll(editParams);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);//表单类型
        for (Map.Entry<String, String> entry : mRequestMap.entrySet()) { //添加普通参数
            builder.addFormDataPart(entry.getKey(),entry.getValue());
        }

        if(file!=null){ //添加图片参数
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("resourceFile", file.getName(), imageBody);//memberImgFile 后台接收图片流的参数名
        }

        List<MultipartBody.Part> parts = builder.build().parts();

        mRetrofitService.updateCompanyHonorOrQuarantine(parts)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriber);
    }

    public void deleteCompanyResource(Map<String, String> params, SubscriberObserver<BaseBean> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(params);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.deleteCompanyResource(mRequestMap)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }

    //验证码
    public void smsVerification(Map<String, String> params, SubscriberObserver<BaseBean> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(params);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.smsVerification(mRequestMap)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }

    //修改密码
    public void changePassword(Map<String, String> params, SubscriberObserver<BaseBean> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(params);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.changePassword(mRequestMap)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }



    public void upDataCopImgOrVideo(Map<String, String> editParams2, File file, Bitmap localVideoThumbnail, SubscriberObserver<BaseBean> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(editParams2);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);//表单类型
        for (Map.Entry<String, String> entry : mRequestMap.entrySet()) { //添加普通参数
            builder.addFormDataPart(entry.getKey(),entry.getValue());
        }

        if(file!=null){ //添加图片参数
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("resourceFile", file.getName(), imageBody);//memberImgFile 后台接收图片流的参数名
        }

        if(localVideoThumbnail!=null){//视频略缩图
            Bitmap bitmap = BitmapUtil.centerSquareScaleBitmap(localVideoThumbnail,400);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            bitmap.recycle();
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), baos.toByteArray());
            builder.addFormDataPart("videoImgResourceFile", "video.png", imageBody);//memberImgFile 后台接收图片流的参数名
        }

        List<MultipartBody.Part> parts = builder.build().parts();

        mRetrofitService.upDataCopImgOrVideo(parts)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void upDataCopInfo(Map<String, String> params, SubscriberObserver<BaseBean> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(params);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.upDataCopInfo(mRequestMap)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void getProvince(SubscriberObserver<BaseBean<List<NewProvinceBean>>> subscriberObserver) {
        getRequestMap();
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.getProvince(mRequestMap)
                .compose(RxHelper.<BaseBean<List<NewProvinceBean>>>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void getCity(SubscriberObserver<BaseBean<List<NewCityBean>>> subscriberObserver,String provinceId) {
        getRequestMap();
        mRequestMap.put("provinceId",provinceId);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.getCity(mRequestMap)
                .compose(RxHelper.<BaseBean<List<NewCityBean>>>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void getArea(SubscriberObserver<BaseBean<List<NewAreaBean>>> subscriberObserver,String cityId) {
        getRequestMap();
        mRequestMap.put("cityId",cityId);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.getArea(mRequestMap)
                .compose(RxHelper.<BaseBean<List<NewAreaBean>>>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void updateUserRole(Map<String, String> params, SubscriberObserver<BaseBean> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(params);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.updateUserRole(mRequestMap)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void addFlowRecored(Map<String, String> params2, List<File> files,SubscriberObserver<BaseBean> subscriberObserver) {

        getRequestMap();
        mRequestMap.putAll(params2);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);//表单类型
        for (Map.Entry<String, String> entry : mRequestMap.entrySet()) { //添加普通参数
            builder.addFormDataPart(entry.getKey(),entry.getValue());
        }

        if(files!=null){ //添加图片参数
            for(File e:files){
                /*String fileSize = String.valueOf(FileSizeUtil.getFileOrFilesSize(e.getPath(),3));
                Log.e("file-size",fileSize+"\n") ;*/
                RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"),getimage(e.getPath()));
                builder.addFormDataPart("resourceFiles", e.getName(), imageBody);//memberImgFile 后台接收图片流的参数名
            }
        }

        List<MultipartBody.Part> parts = builder.build().parts();

        mRetrofitService.addFlowRecored(parts)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }


    public void addFlowRecoredBytes(Map<String, String> params2, List<byte[]> files,SubscriberObserver<BaseBean> subscriberObserver) {

        getRequestMap();
        mRequestMap.putAll(params2);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);//表单类型
        for (Map.Entry<String, String> entry : mRequestMap.entrySet()) { //添加普通参数
            builder.addFormDataPart(entry.getKey(),entry.getValue());
        }

        if(files!=null){ //添加图片参数
            for(byte[] e:files){
                RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"),e);
                builder.addFormDataPart("resourceFiles","image.png", imageBody);//memberImgFile 后台接收图片流的参数名
            }
        }

        List<MultipartBody.Part> parts = builder.build().parts();

        mRetrofitService.addFlowRecored(parts)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }

    //图片压缩
   private byte[] getimage(String srcPath) {
        return compressImage(BitmapFactory.decodeFile(srcPath));//进行质量压缩
    }


    private byte[] compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 80;
        while ( baos.toByteArray().length / 1024>300) { //循环判断如果压缩后图片是否大于1m,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 20;//每次都减少20
        }
        image.recycle();
        return baos.toByteArray();
      /*  ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;*/
    }

    public void queryRecordingList(Map<String, String> params, SubscriberObserver<BaseBean<OprationRecoredListBean>> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(params);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.queryRecordingList(mRequestMap)
                .compose(RxHelper.<BaseBean<OprationRecoredListBean>>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void finishFlow(Map<String, String> params, SubscriberObserver<BaseBean> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(params);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.finishFlow(mRequestMap)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void getBatchList(String userId, SubscriberObserver<BaseBean<BatchManagementBean>> subscriberObserver) {
        getRequestMap();
        mRequestMap.put("userId",userId);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.getBatchList(mRequestMap)
                .compose(RxHelper.<BaseBean<BatchManagementBean>>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void addProductInfo(Map<String, String> params2, List<File> files, SubscriberObserver<BaseBean> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(params2);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);//表单类型
        for (Map.Entry<String, String> entry : mRequestMap.entrySet()) { //添加普通参数
            builder.addFormDataPart(entry.getKey(),entry.getValue());
        }

        if(files!=null){ //添加图片参数
            for(File e:files){

                RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), getimage(e.getPath()));

              //  RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), e);
                builder.addFormDataPart("resourceFiles", e.getName(), imageBody);//memberImgFile 后台接收图片流的参数名
            }
        }

        List<MultipartBody.Part> parts = builder.build().parts();

        mRetrofitService.addProductInfo(parts)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void changeBatchNameOrState(Map<String, String> params, SubscriberObserver<BaseBean> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(params);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.changeBatchNameOrState(mRequestMap)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void resetUseMobile(Map<String, String> params, SubscriberObserver<BaseBean> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(params);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.resetUseMobile(mRequestMap)
                .compose(RxHelper.<BaseBean>schedulersThread())
                .subscribe(subscriberObserver);
    }

    public void getSysPermission(Map<String, String> params, SubscriberObserver<BaseBean<SysAuthDataBean>> subscriberObserver) {
        getRequestMap();
        mRequestMap.putAll(params);
        mRequestMap.put("sign", MD5Utils.encrypt16(StringUtils.sortValueByKey(mRequestMap)));
        mRetrofitService.getSysPermission(mRequestMap)
                .compose(RxHelper.<BaseBean<SysAuthDataBean>>schedulersThread())
                .subscribe(subscriberObserver);
    }
}